class Solution
{
public:
    int earliestSecondToMarkIndices(vector<int> &nums, vector<int> &changeIndices)
    {
        int n = nums.size();
        long long sum = 0;
        for (int i = 0; i < n; i++)
        {
            sum += nums[i];
        }
        int m = changeIndices.size();
        if (sum + n > m)
        {
            return -1;
        }
        int getAllIndexTime = -1;
        unordered_set<int> indexSet;
        for (int i = 0; i < m; i++)
        {
            indexSet.insert(changeIndices[i]);
            if (indexSet.size() == n)
            {
                getAllIndexTime = i + 1;
                break;
            }
        }
        if (getAllIndexTime == -1)
        {
            return -1;
        }

        auto checkAnswer = [&](int time) -> bool
        {
            vector<pair<int, int>> indexLastOccur(n);
            for (int i = 0; i < n; i++)
            {
                indexLastOccur[i] = {i, -1};
            }

            for (int i = 0; i < time; i++)
            {
                indexLastOccur[changeIndices[i] - 1].second = i + 1;
            }

            sort(indexLastOccur.begin(), indexLastOccur.end(), [](pair<int, int> &a, pair<int, int> &b)
                 { return a.second < b.second; });

            int timeUsed = 0;
            for (auto [index, lastOccur] : indexLastOccur)
            {
                if (timeUsed + nums[index] + 1 <= lastOccur)
                {
                    timeUsed += nums[index] + 1;
                }
                else
                {
                    return false;
                }
            }
            return true;
        };

        int left = max(int(sum + n), getAllIndexTime);
        int right = m;
        while (left < right)
        {
            int mid = (left + right) / 2;
            if (checkAnswer(mid))
            {
                right = mid;
            }
            else
            {
                left = mid + 1;
            }
        }
        return left;
    }
};